package com.qcxy.gzy.activity;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

import com.qcxy.gyz.consts.CMDConts;
import com.qcxy.gzy.activity.base.BaseActivity;
import com.qcxy.gzy.bean.ComReceiveDataBean;
import com.qcxy.gzy.view.CircleChartView;
import com.qxcy.gzy.util.DataCovertUtil;
import com.qxcy.gzy.util.SPUtils;

public class FitnessCustomStartActivity extends BaseActivity implements OnClickListener{

	private int mWeight1;
	private int mWeight2;
	private int mWeight3;
	private boolean firstTime = true;
	 /** 计算器 */
	private Calendar mCalendar = Calendar.getInstance();
	
	private TextView showTargetNumber;
	private TextView mTimeTv;
	private TextView mCalorieTv;
	private TextView mShowWeight;
	private CircleChartView  mDialChartView;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_fitness_custom_start);
		
		mWeight1 = Integer.parseInt(SPUtils.getValueFromSharedFile(FitnessCustomStartActivity.this, "mWeight1", "0"));
		mWeight2 = Integer.parseInt(SPUtils.getValueFromSharedFile(FitnessCustomStartActivity.this, "mWeight2", "0"));
		mWeight3 = Integer.parseInt(SPUtils.getValueFromSharedFile(FitnessCustomStartActivity.this, "mWeight3", "0"));
		if(mWeight1<10){
			mWeight1 = 10;
		}
		if(mWeight2<10){
			mWeight2 = 10;
		}
		if(mWeight3<10){
			mWeight3 = 10;
		}
		
		showTargetNumber = (TextView) findViewById(R.id.report_number);
		mTimeTv = (TextView) findViewById(R.id.report_number2);
		mCalorieTv = (TextView) findViewById(R.id.report_number3);
		mShowWeight = (TextView) findViewById(R.id.report_number4);
		mDialChartView = (CircleChartView) findViewById(R.id.myview_circle_chart);
		
		findViewById(R.id.iv_back).setOnClickListener(this);
		
		mSendThread = new SendThread(getForceCMD(), false);
        mSendThread.start();
	}
	
    protected List<byte[]> getForceCMD() {
        List<String> forceList = null;
        StringBuilder sDistance_D2 = new StringBuilder(); // 存放写入力量寄存器2命令
        StringBuilder sDistance_D3 = new StringBuilder(); // 存放写入力量寄存器2命令
        StringBuilder sDistance_D4 = new StringBuilder(); // 存放写入力量寄存器2命令
        StringBuilder sDistance_D5 = new StringBuilder(); // 存放写入力量寄存器2命令
//        int distance_3 = 0; // 存放距离寄存器3的值
        List<byte[]> cmdList = new ArrayList<byte[]>(); // 命令列表
        List<String> forceHeadList = new ArrayList<String>(); // 写入力量命令列表
        forceHeadList.add(CMDConts.CMD_WRITE_REIGSTER_F1); // 添加命令头部
        forceHeadList.add(CMDConts.CMD_WRITE_REIGSTER_F2);
        forceHeadList.add(CMDConts.CMD_WRITE_REIGSTER_F3);
        forceHeadList.add(CMDConts.CMD_WRITE_REIGSTER_F4);
        forceHeadList.add(CMDConts.CMD_WRITE_REIGSTER_F5);
        cmdList.add(CMDConts.CMD_WRITE_REIGSTER_F0);
        forceList = getProtForce();
        if (forceList != null) {
            for (int i = 0; i < forceHeadList.size(); i++) {
                StringBuilder sBuilder = new StringBuilder();
                sBuilder.append(forceHeadList.get(i)); // 添加头部
                sBuilder.append(forceList.get(i)); // 添加力量值
                // 获得并添加CRC校验码
                cmdList.add(DataCovertUtil.getCRC(DataCovertUtil.HexToByteArr(sBuilder.toString())));
            }
        }
//        distance_3 = (80 + 3500) / 2; // 计算距离寄存器D3的值
        sDistance_D2.append(CMDConts.CMD_WRITE_REIGSTER_D2); // 添加头部
        sDistance_D2.append(DataCovertUtil.get4LenString(Integer.toHexString(700))); // 计算并添加距离值
        sDistance_D3.append(CMDConts.CMD_WRITE_REIGSTER_D3); // 添加头部
        sDistance_D3.append(DataCovertUtil.get4LenString(Integer.toHexString(1400))); // 添加距离值
        sDistance_D4.append(CMDConts.CMD_WRITE_REIGSTER_D4); // 添加头部
        sDistance_D4.append(DataCovertUtil.get4LenString(Integer.toHexString(2100)));// 添加距离值
        sDistance_D5.append(CMDConts.CMD_WRITE_REIGSTER_D5); // 添加头部
        sDistance_D5.append(DataCovertUtil.get4LenString(Integer.toHexString(3500))); // 添加距离值
        cmdList.add(CMDConts.CMD_WRITE_REIGSTER_D0); // 添加距离寄存器D0的命令
        cmdList.add(CMDConts.CMD_WRITE_REIGSTER_D1); // 添加距离寄存器D1的命令
        cmdList.add(DataCovertUtil.getCRC(DataCovertUtil.HexToByteArr(sDistance_D2.toString()))); // 计算并添加距离寄存器D2命令的CRC校验码
        cmdList.add(DataCovertUtil.getCRC(DataCovertUtil.HexToByteArr(sDistance_D3.toString()))); // 计算并添加距离寄存器D3命令的CRC校验码
        cmdList.add(DataCovertUtil.getCRC(DataCovertUtil.HexToByteArr(sDistance_D4.toString()))); // 计算并添加距离寄存器D4命令的CRC校验码
        cmdList.add(DataCovertUtil.getCRC(DataCovertUtil.HexToByteArr(sDistance_D5.toString()))); // 计算并添加距离寄存器D5命令的CRC校验码
        cmdList.add(CMDConts.CMD_READ_REGISTER_3_4); // 添加读取寄存器3、4命令
        return cmdList;
    }

	/**
     * 获得变力力量
     * 
     * @return
     */
    private List<String> getProtForce() {
        int force1 = mWeight1 * 333 / 10;
        int force3 = mWeight2 * 333 / 10;
        int force5 = mWeight3 * 333 / 10;
        int force2 = (force1 + force3) / 2;
        int force4 = (force3 + force5) / 2;
        List<String> list = new ArrayList<String>();
        list.add(DataCovertUtil.get4LenString(Integer.toHexString(force1))); // 获得四位字符串型力量的值
        list.add(DataCovertUtil.get4LenString(Integer.toHexString(force2))); // 获得四位字符串型力量的值
        list.add(DataCovertUtil.get4LenString(Integer.toHexString(force3))); // 获得四位字符串型力量的值
        list.add(DataCovertUtil.get4LenString(Integer.toHexString(force4))); // 获得四位字符串型力量的值
        list.add(DataCovertUtil.get4LenString(Integer.toHexString(force5))); // 获得四位字符串型力量的值
        return list;
    }
    
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()){
		case R.id.iv_back: 
			FitnessCustomStartActivity.this.finish();
			break;
		}
	}
	
	private void resetCalendar() {
		mCalendar.set(Calendar.HOUR_OF_DAY, 0);
		mCalendar.set(Calendar.MINUTE, 0);
		mCalendar.set(Calendar.SECOND, 0);
	}
	
	private Timer timer;

	private void showClock(TextView tv) {
		timer = new Timer();
		timer.schedule(new TrainTask(tv), 1000, 1000);
	}

	private class TrainTask extends TimerTask {
		public TrainTask(TextView tv) {
			mTimeTv = tv;
		}

		@Override
		public void run() {
			runOnUiThread(new Runnable() {
				public void run() {
					// 每次秒数+1
					mCalendar.add(Calendar.SECOND, 1);
					mTimeTv.setText(DataCovertUtil.get2LenString(mCalendar.get(Calendar.MINUTE)) + ":" + DataCovertUtil.get2LenString(mCalendar.get(Calendar.SECOND)));
				}
			});
		}
	}
	
	private Timer mTimer4LogOut = null;
    
    private void resetTimer4LogOut() {
		if (mTimer4LogOut != null) {
			mTimer4LogOut.cancel();
			mTimer4LogOut.purge();
			mTimer4LogOut = null;
		}
		mTimer4LogOut = new Timer();
		// 1分钟不操作自动上传数据
		mTimer4LogOut.schedule(new Task4Logout(), 1 * 60 * 1000);
	}
    
    private class Task4Logout extends TimerTask {
		@Override
		public void run() {
			runOnUiThread(new Runnable() {
				public void run() {
					// uploadTrainningData();
					FitnessCustomStartActivity.this.finish();
				}
			});
		}
	}
	
	private int distance = 0;
	private int weight = 0;
	
	@Override
	protected void onDataReceived(ComReceiveDataBean ComRecData) {
		if (ComRecData.getCRC(ComRecData.bRec).equals("0")) {
			String res = DataCovertUtil.ByteArrToHex(ComRecData.bRec);
			final int control = DataCovertUtil.HexToInt(DataCovertUtil
					.ByteArrToHex(ComRecData.bRec).substring(2, 4));
			if (control == 3) { // control指的返回的命令区分码
				// 实时值
				weight = DataCovertUtil.HexToInt(res.substring(6, 10));
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						mShowWeight.setText((int)(weight / 33.33)+"");
					}
				});
				
				distance = DataCovertUtil.HexToInt(res.substring(10,14));
				if (distance > 150) {
					if (firstTime) {
						resetCalendar();
						showClock(mTimeTv);
						firstTime = false;
					}
					resetTimer4LogOut();
				}

				if (distance >= 1500) { // 检测到距离大于60%最大距离时
					mStatus = 1; // 拉伸状态变为1
					if (distance4Calorie < distance) {
						distance4Calorie = distance;
					}
				}

				// 拉伸状为1并且 检测到距离小于30%最大距离时拉伸状态变为
				if (mStatus == 1 && distance < 1500) {
					mRealCounts++; // 次数 + 1
					mStatus = 0; // 拉伸状态清除
					
					if (distance4Calorie >= 1500 && distance4Calorie < 2000) {
						calorie = calorie + (weight / (180 + (Math.random() * 40)));
					} else if (distance4Calorie >= 2000 && distance4Calorie < 3000) {
						calorie = calorie + (weight / (130 + (Math.random() * 40)));
					} else {
						calorie = calorie + (weight / (80 + (Math.random() * 40)));
					}
				}
				
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						showTargetNumber.setText(mRealCounts + "");
						mCalorieTv.setText(String.format("%.1f",calorie));
						mDialChartView.setPercent(distance * 100 / 3500, 3500 * 100 / 3500);
					}
				});
			}
		}
	}
}
